package com.aifast.core.dataScope;

import cn.hutool.core.util.ObjectUtil;
import com.aifast.common.dataScope.DataScope;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author fujian
 * @since 2022/5/18 9:10
 * 数据权限aop 根据dao层接口设置对应的数据权限
 * aop这里只做对应的用户权限信息获取并生成权限sql片段 传到上下文 由mp拦截器来完成sql的拼接和修改工作
 */
@Aspect
@Component
public class DataScopeAspect {

    @Pointcut("@annotation(com.aifast.common.dataScope.DataScope)")
    public void cut() {
    }

    @Before("cut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        DataScope dataScope = getAnnotation(joinPoint);
        if (ObjectUtil.isNotNull(dataScope)) {
            DataScopeContextHolder.set(dataScope);
        }
    }

    @After("cut()")
    public void after(JoinPoint joinPoint) {
        DataScopeContextHolder.remove();
    }

    /**
     * 获取dataScope的注解
     */
    private DataScope getAnnotation(JoinPoint point) {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        return null != method ? method.getAnnotation(DataScope.class) : null;
    }

}
